from typing import Optional
from sqlalchemy import select, and_
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus

from modules.system.models.dict_item import Dictionary
from modules.system.schemas.dict_item_schemas import DictItemCreate, DictItemUpdate


class DictItemRepository(CRUDPlus[Dictionary]):
    async def get_by_id(self, db: AsyncSession, pk: int) -> Optional[Dictionary]:
        return await self.select_model_by_column(db, id=pk, status=1)

    async def get_by_key_and_type(self, db: AsyncSession, dict_key: str, dict_type: str) -> Optional[Dictionary]:
        res = await db.execute(
            select(Dictionary).where(and_(Dictionary.dict_key == dict_key, Dictionary.dict_type == dict_type))
        )
        return res.scalar_one_or_none()

    async def create(self, db: AsyncSession, data: DictItemCreate) -> Dictionary:
       return await self.create_model(db, data)

    async def update(self, db: AsyncSession, pk: int, data: DictItemUpdate) -> Optional[Dictionary]:
        await self.update_model(db, pk, data)
        return await self.select_model(db, pk)

    async def delete(self, db: AsyncSession, pk: int) -> bool:
        return await self.delete_model(db, pk)


dict_item_dao = DictItemRepository(Dictionary)